<?php
namespace app\controller;

use app\validate\Users as UserValidate;
use think\captcha\facade\Captcha;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\response\Json;
use utils\HashID;
use app\model\User as UserModel;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Account
{
    public function index()
    {
        return abort(403);
    }


    /**
     * 用户登录
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(Request $request): Json
    {
        // 清除过期限制记录
        UserModel::clearExpiredLimits();
        
        $ip = $request->ip();
        
        // 检查是否超过登录尝试次数
        if (!UserModel::checkLoginLimit($ip)) {
            return apiResponse(400, '登录失败次数过多，请1小时后再试');
        }
        
        $data = $request->post();

        // 验证用户名和密码
        $user = UserModel::whereOr('username', $data['username'])
            ->whereOr('mobile', $data['username'])
            ->whereOr('email', $data['username'])
            ->find();
        if (!$user || !password_verify($data['password'], $user['password'])) {
            UserModel::logFailedLoginAttempt($ip);
            return apiResponse(400, '用户名或密码错误');
        }
        
        // 登录成功，更新用户信息
        $user->last_login_ip = $ip;
        $user->last_login_time = time();
        $user->save();
        
        // 生成JWT token
        $config = config('jwt');
        $payload = [
            'user_id' => $user['id'],
            'username' => $user['username'],
            'exp' => time() + $config['expire'] * 3600, // 过期时间
            'iat' => time(), // 签发时间
        ];
        $token = JWT::encode($payload, $config['secret'], $config['algorithm']);

        $data = [
            'userinfo' => [
                'id' => $user['id'],
                'username' => $user['username'],
                'mobile' => $user['mobile'],
                'email' => $user['email'],
                'avatar' => $user['avatar'], // 头像
            ],
            'token' => $token,
        ];
        return apiResponse(200, '登录成功,正在为您跳转到管理首页...', $data);
    }

    /**
     * 新用户注册
     * @param Request $request
     * @return Json
     */
    public function register(Request $request): Json
    {
        // 清除过期限制记录
        UserModel::clearExpiredLimits();
        
        $ip = $request->ip();
        
        // 检查IP注册限制（例如：1小时内最多注册3个账号）
        if (!UserModel::checkRegisterLimit($ip, 3, 3600)) {
            return apiResponse(400, '当前IP注册次数过多，请稍后再试');
        }
        
        $data = $request->post();
        if(!$data['captcha'] || ! Captcha::check($data['captcha'])){
            UserModel::logRegisterAttempt($ip);
            return apiResponse(400,'验证码错误');
        }
        //校验验证码
        $validate = new UserValidate();
        if(!$validate->check($data)){
            UserModel::logRegisterAttempt($ip);
            return apiResponse(400,$validate->getError());
        }
        //组合数据
        $data = [
            'id' => HashID::generate(24),
            'username' => $data['username'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
            'mobile' => $data['mobile'],
            'reg_ip'=> $request->ip(),
            'reg_time' => time(),
            'last_login_ip' => $request->ip(),
            'last_login_time' => time(),
        ];
        //写入用户数据
        try {
            //避免ID重复
            while (UserModel::where('id',$data['id'])->find()){
                $data['id'] = HashID::generate(24);
            }
            UserModel::create($data);
            // 注册成功，记录注册尝试
            UserModel::logRegisterAttempt($ip);
            return apiResponse(200,'注册成功,正在为您跳转到登录页面...');
        }catch (\Exception $e){
            UserModel::logRegisterAttempt($ip);
            return apiResponse($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 刷新token
     * @param Request $request
     * @return Json
     */
    public function refresh_token(Request $request): Json
    {
        // 获取请求头中的Authorization
        $authHeader = $request->header('Authorization');
        
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return apiResponse(401, '缺少有效的token');
        }
        
        $token = substr($authHeader, 7); // 移除 'Bearer ' 前缀
        
        // 获取JWT配置
        $config = config('jwt');
        
        try {
            // 解码token
            $decoded = JWT::decode($token, new Key($config['secret'], $config['algorithm']));
            
            // 检查用户是否存在
            $user = UserModel::where('id', $decoded->user_id)->find();
            if (!$user) {
                return apiResponse(401, '用户不存在');
            }
            
            // 生成新的token
            $payload = [
                'user_id' => $user['id'],
                'username' => $user['username'],
                'exp' => time() + $config['expire'] * 3600, // 过期时间
                'iat' => time(), // 签发时间
            ];
            $newToken = JWT::encode($payload, $config['secret'], $config['algorithm']);
            
            // 返回新token
            $result = [
                'token' => $newToken,
                'expire_in' => $config['expire'] * 3600 // 过期时间（秒）
            ];
            
            return apiResponse(200, 'token刷新成功', $result);
        } catch (\Exception $e) {
            return apiResponse(401, 'token无效或已过期');
        }
    }
}